﻿namespace ScrumSprintMonitor.Modules.BuildMonitor.Controls
{
	#region #using Directives

	using System;
	using System.ComponentModel;
	using System.Windows;
	using System.Windows.Controls;
	using System.Windows.Media;
	using System.Windows.Media.Animation;
	using System.Windows.Threading;

	using ViewModels;

	#endregion

	/// <summary>
	/// Interaction logic for BuildStatusBorder.xaml
	/// </summary>
	public partial class BuildStatusBorder : Grid
	{
		private IBuildStatusBackgroundViewModel buildStatusBackgroundViewModel;

		public BuildStatusBorder()
		{
			InitializeComponent();
		}

		private void OnDataContextChanged()
		{
			if (this.buildStatusBackgroundViewModel != DataContext)
			{
				if (this.buildStatusBackgroundViewModel != null)
				{
					this.buildStatusBackgroundViewModel.PropertyChanged -= OnBuildStatusBackgroundViewModelPropertyChanged;
					this.buildStatusBackgroundViewModel = null;
				}

				this.buildStatusBackgroundViewModel = (IBuildStatusBackgroundViewModel) DataContext;
				if (this.buildStatusBackgroundViewModel != null)
				{
					this.buildStatusBackgroundViewModel.PropertyChanged += OnBuildStatusBackgroundViewModelPropertyChanged;
				}
			}
		}

		private void OnGridLoaded(object sender, RoutedEventArgs e)
		{
			OnDataContextChanged();

			// Remove any databinding
			if (Background == null)
			{
				Background = new SolidColorBrush(this.buildStatusBackgroundViewModel.BuildStatusColor);
			}
			else
			{
				Background = Background.CloneCurrentValue();
			}
		}

		private void OnGridDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
		{
			OnDataContextChanged();
		}

		private void OnBuildStatusBackgroundViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			switch (e.PropertyName)
			{
				case "BuildStatusColor":
					Dispatcher.BeginInvoke(new Action<Grid, Color>(BeginAnimation), DispatcherPriority.Background, this,
					                       this.buildStatusBackgroundViewModel.BuildStatusColor);
					break;
			}
		}

		private static void BeginAnimation(Grid grid, Color targetColor)
		{
			grid.Background.BeginAnimation(SolidColorBrush.ColorProperty, new ColorAnimation(targetColor, new Duration(TimeSpan.FromSeconds(5.0))));
		}
	}
}